from datetime import datetime, timedelta
from apps.core.utils import date_time as datetime_helper
from django.utils import timezone
from rest_framework.exceptions import ValidationError


def validate_checkin(appointment, value):
    if appointment is None:
        return value

    start_date = appointment.booking.start_date if appointment.booking else appointment.start_date
    start_time = appointment.booking.start_time if appointment.booking else appointment.start_time
    end_time = appointment.booking.end_time if appointment.booking else appointment.end_time

    if appointment.checked_in and appointment.clients is not None and value:
        raise ValidationError('Already checked-in')

    start_datetime = timezone.make_aware((datetime.combine(start_date.date(), start_time)),
                                         timezone.get_current_timezone()) - timedelta(minutes=15)
    end_datetime = timezone.make_aware((datetime.combine(start_date.date(), end_time)),
                                       timezone.get_current_timezone())

    start_datetime = start_datetime.replace(tzinfo=None)
    end_datetime = end_datetime.replace(tzinfo=None)

    now = datetime_helper.now()
    if now < start_datetime or now > end_datetime:
        raise ValidationError('Invalid check-in time. You can only check-in from 15 mins. prior the '
                                          'start time')

    return value